using System.Collections.Generic;
using System.IO;
using System.Linq;
using Gj;
using SimpleJSON;
using UnityEditor;
using UnityEditor.UIElements;
using UnityEngine;
using UnityEngine.UIElements;

namespace DefaultNamespace
{
    public class SwitchToken : EditorWindow
    {
        private ListView RightPane;
        private Label EnvironmentLabel;
        private Label UserNameLabel;
        private Label UserTokenLabel;

        private

        SwitchToken()
        {
            titleContent = new GUIContent("切换账号");
        }

        [MenuItem("Gj/切换账号")]
        static void CreateTestWindows()
        {
            GetWindow(typeof(SwitchToken));
        }
        public void CreateGUI()
        {
            Project.LoadEnvironmentInfo();
            Project.LoadUserInfo();
            Project.Base();

            var splitView = new TwoPaneSplitView(0, 250, TwoPaneSplitViewOrientation.Horizontal);

            // Add the view to the visual tree by adding it as a child to the root element
            rootVisualElement.Add(splitView);

            // A TwoPaneSplitView always needs exactly two child elements
            var leftPane = new VisualElement();
            splitView.Add(leftPane);
            EnvironmentLabel = new Label();
            EnvironmentLabel.text = Project.EnvironmentSetting.gameLink;
            leftPane.Add(EnvironmentLabel);
            UserNameLabel = new Label();
            if (Project.UserSetting != null)
            {
                UserNameLabel.text = Project.UserSetting.userName + "(" + Project.UserSetting.userId + ")";
            }
            else
            {
                UserNameLabel.text = "";
            }
            leftPane.Add(UserNameLabel);
            UserTokenLabel = new Label();
            if (Project.UserSetting != null)
            {
                UserTokenLabel.text = Project.UserSetting.token;
            }
            else
            {
                UserTokenLabel.text = "";
            }
            leftPane.Add(UserTokenLabel);

            var userKeyword = new TextField();
            userKeyword.label = "user keyword";
            userKeyword.value = "";
            // if (Project.UserSetting != null)
            // {
            //     userKeyword.value = Project.UserSetting.userName;
            // }
            // else
            // {
            //     userKeyword.value = "";
            // }
            leftPane.Add(userKeyword);
            var userPage = new IntegerField();
            userPage.label = "Page";
            userPage.value = 1;
            leftPane.Add(userPage);
            var userNumber = new IntegerField();
            userNumber.label = "Number";
            userNumber.value = 10;
            leftPane.Add(userNumber);

            var updateButton = new Button() { text = "更新" };
            updateButton.clicked += () =>
            {
                //加载
                var d = Manager.SearchUser(userKeyword.value, userNumber.value, userPage.value, (list) =>
                {
                    RightPane.itemsSource?.Clear();
                    if (list == null)
                    {
                        return;
                    }
                    var allObjects = new List<JSONObject>();
                    foreach (var user in list)
                    {
                        Debug.LogError(user as JSONObject);
                        allObjects.Add(user as JSONObject);
                    }

                    RightPane.makeItem = () => new Label();
                    RightPane.bindItem = (item, index) =>
                    {
                        Debug.LogError("switch:"+index+"->"+allObjects.Count);
                        var label = (item as Label);
                        label.text = allObjects[index]["userName"];
                    };
                    RightPane.itemsSource = allObjects;
                });
                while (d.MoveNext())
                {
                }

                RightPane.RefreshItems();
            };
            leftPane.Add(updateButton);
            var clearButton = new Button() { text = "清空" };
            clearButton.clicked += () =>
            {
                Project.UserSetting.token = "";
                Project.UserSetting.userId = "";
                Project.UserSetting.userName = "";
                UserNameLabel.text = "";
                UserTokenLabel.text = "";
                var a = JsonUtility.ToJson(Project.UserSetting);
                ChangeUser(a);
            };
            leftPane.Add(clearButton);

            RightPane = new ListView();
            splitView.Add(RightPane);
            RightPane.onSelectionChange += OnUserSelectChange;
        }

        private void OnUserSelectChange(IEnumerable<object> selectedItems)
        {
            // 切换账号
            var item = selectedItems.First() as JSONObject;
            Debug.LogError("select:"+selectedItems.First());
            Debug.LogError("current:"+Project.UserSetting.token);
            if (Project.UserSetting != null)
            {
                if (item["token"] == Project.UserSetting.token)
                {
                    return;
                }
            }
            else
            {
                Project.UserSetting = new UserSetting();
            }

            Project.UserSetting.token = item["token"];
            Project.UserSetting.userId = item["userId"];
            Project.UserSetting.userName = item["userName"];
            var a = JsonUtility.ToJson(Project.UserSetting);
            ChangeUser(a);
            UserNameLabel.text = Project.UserSetting.userName + "(" + Project.UserSetting.userId + ")";
            UserTokenLabel.text = Project.UserSetting.token;
        }
        static private void ChangeUser(string json)
        {
            Debug.Log("update user setting:" + json);
            var settings = Path.Combine(Application.absoluteURL, Project.userFile);
            using (StreamWriter sw = new StreamWriter(settings))
            {
                sw.WriteLine(json);
            }
        }
    }
}